local Globals = require('lua.vm.Globals')
local LuaCompiler = require('lua.vm.compiler.LuaCompiler')
local CfgState = require('lua.cfg.CfgState')
local ByteArrayInputStream = require('lua.io.ByteArrayInputStream')
local FileOutputStream = require('lua.io.FileOutputStream')

local src = [[
-- 测试 if, for, while, goto 的 Lua 代码
x = 10
y = 0
z = 5

-- if 语句测试
if x > 5 then
	y = 1
elseif x == 5 then
	y = 2
else
	y = 3
end

-- for 循环测试
sum = 0
for i = 1, 10 do
	sum = sum + i
	if i == 5 then
		break
	end
end

-- while 循环测试
counter = 0
while counter < 5 do
	counter = counter + 1
	if counter == 3 then
		goto skip_three
	end
	:: continue ::
end

-- goto 测试
:: skip_three ::
z = z * 2

-- 嵌套控制结构测试
for j = 1, 3 do
	k = 0
	while k < 2 do
		if j == 2 and k == 1 then
			goto end_loop
		end
		k = k + 1
	end
end

:: end_loop ::
result = x + y + z + sum + counter

-- 最终的复杂控制流
if result > 50 then
	for m = 1, 3 do
		n = 0
		while n < m do
			if n == 1 then
				goto next_iteration
			end
			:: next_iteration ::
			n = n + 1
		end
	end
end
]]

local workDir = 'E:\\lua Project\\'
local bis = ByteArrayInputStream:new(src:toByteArray())
local globals = Globals:new()
globals:installCompiler(LuaCompiler)
local p = globals:loadPrototype(bis, 'test.lua', 't')
bis:close()
local state = CfgState:new(p.code)
local g = state:analyze()
local fos = FileOutputStream:new(workDir .. 'cfg.dot')
fos:writeString(g:toDotString())
fos:close()
-- dot -Tpng cfg.dot -o out.png